<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="是否虚拟商品" prop="virtualProduct">
      <el-radio-group
        disabled
        @change="changeVirtualProduct"
        v-model="formData.virtualProduct"
        class="w-80"
      >
        <el-radio :label="true" class="radio">是</el-radio>
        <el-radio :label="false">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="商品名称" prop="name">
    <el-input
      v-model="formData.name"
      :autosize="{ minRows: 2, maxRows: 2 }"
      :clearable="true"
      :show-word-limit="true"
      class="w-80!"
      maxlength="64"
      placeholder="请输入商品名称"
      type="textarea"
    />
  </el-form-item>
<!--    <el-form-item label="商品类型" prop="productType">-->
<!--      <el-select v-model="formData.productType" class="w-80">-->
<!--        <el-option v-for="item in ProductTypeOptionList" :key="item.value" :label="item.text" :value="item.value"/>-->
<!--      </el-select>-->
<!--    </el-form-item>-->
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
      />
    </el-form-item>
<!--    <el-form-item label="充值方式" prop="rechargeMethod">-->
<!--      <el-select placeholder="请选择充值方式" v-model="formData.rechargeMethod" class="w-80">-->
<!--        <el-option-->
<!--          v-for="item in RechargeMethodTypeOptionList"-->
<!--          :key="item.value"-->
<!--          :label="item.text"-->
<!--          :value="item.value"-->
<!--        />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
<!--    <el-form-item label="商品品牌" prop="brandId">-->
<!--      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">-->
<!--        <el-option-->
<!--          v-for="item in brandList"-->
<!--          :key="item.id"-->
<!--          :label="item.name"-->
<!--          :value="item.id as number"-->
<!--        />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
    <el-form-item label="商品排序" prop="sort">
      <el-input-number v-model="formData.sort" :min="1" />
    </el-form-item>
<!--    <el-form-item label="商品关键字" prop="keyword">-->
<!--      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="售价币种" prop="currencyCode">-->
<!--      <el-select @change="changeCurrencyCode" v-model="formData.currencyCode" class="w-80" placeholder="请选择售价币种">-->
<!--        <el-option-->
<!--          v-for="item in currencyList"-->
<!--          :key="item.currencyCode"-->
<!--          :label="item.currencyName"-->
<!--          :value="item.currencyCode"-->
<!--        />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
<!--    <el-form-item label="商品简介" prop="introduction">-->
<!--      <el-input-->
<!--        v-model="formData.introduction"-->
<!--        :autosize="{ minRows: 5, maxRows: 10 }"-->
<!--        :clearable="true"-->
<!--        :show-word-limit="true"-->
<!--        class="w-80!"-->
<!--        maxlength="512"-->
<!--        placeholder="请输入商品简介"-->
<!--        type="textarea"-->
<!--      />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="商品地区" prop="region">-->
<!--        <el-input v-model="formData.region" class="w-80!" placeholder="请输入商品地区" />-->
<!--    </el-form-item>-->
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
<!--    <el-form-item label="商品轮播图" prop="sliderPicUrls">-->
<!--      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="商品详情" prop="description">-->
<!--      <Editor :readonly="isDetail" v-model:modelValue="formData.description" />-->
<!--    </el-form-item>-->
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </el-form>
</template>
<script lang="ts" setup>
import {getCardkeyByNo} from "@/api/digital/cardkeyproduct";

const { t } = useI18n() // 国际化
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import {ExchangeRateApi} from '@/api/mall/currency/rate/index';
import { BrandVO } from '@/api/mall/product/brand'
import {
  EnumCurrencyCodeType,
  EnumProductType,
  EnumRechargeMethodType, EnumTradeDeliveryType, EnumUserCustomInputType,
  ProductTypeOptionList,
  RechargeMethodTypeOptionList
} from "@/config/spu";
import {Editor} from "@/components/Editor";
import {useTagsViewStore} from "@/store/modules/tagsView";
import {cloneDeep} from "lodash-es";
import * as ProductSpuApi from "@/api/mall/product/spu";
const { push, currentRoute } = useRouter() // 路由
const { delView } = useTagsViewStore() // 视图操作

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  id: propTypes.number.def(undefined),
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗
const formLoading = ref(false);
const formRef = ref() // 表单 Ref
const currencyList = ref([]);
const formData = ref<Spu>({
  virtualProduct: true, // 是否虚拟商品
  rechargeMethod: EnumRechargeMethodType.CARD_CODE, // 充值方式
  region: "", // 商品区域
  productType: EnumProductType.ESIM_CARD, // 商品类型
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  currencyCode: undefined,
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  brandId: undefined, // 商品品牌,
  description: "", // 商品详情
  sort: 0, // 商品排序
  giveIntegral: 0, // 赠送积分
  virtualSalesCount: 0, // 虚拟销量
  specType: true, // 商品规格
  subCommissionType: false, // 分销类型
})
const rules = reactive({
  virtualProduct: [required],
  // productType: [required],
  // rechargeMethod: [required],
  // currencyCode: [required],
  // region: [required],
  name: [required],
  categoryId: [required],
  // keyword: [required],
  // introduction: [required],
  picUrl: [required],
  // sliderPicUrls: [],
  // brandId: [required],
  // description: [required],
  sort: [required],
})

watch(
  () => formData.value.description,
  (newValue) => {
    if ('<p><br></p>' === newValue) {
      formData.value.description = ''
    }
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['changeVirtualProduct'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
  } catch (e) {
    formLoading.value = false;
    message.error('必填字段项不完整，请输入后提交')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

function changeVirtualProduct() {
  emit("changeVirtualProduct", formData.value.virtualProduct)
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductSpu' })
}

const getDetail = async ()=> {
  if(props.id) {
    const res = (await ProductSpuApi.getSpu(props.id)) as ProductSpuApi.Spu

    // formData.value = res
    Object.assign(formData.value, res);
  }
}

const changeCurrencyCode = async ()=> {
  if(formData.value.skus && formData.value.skus.length) {
    message.alert("系统检测到已经添加过商品sku，如有关联CDK，请确认货币类型是否一致");
  }
}

const submitForm = async ()=> {
  formLoading.value = true

  // 校验表单数据
  await validate();

  let deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu;

  delete deepCopyFormData.skus;
  const id = props.id as unknown as number
  try {
    if (!id) {
      let resId = await ProductSpuApi.createSpu(deepCopyFormData);
      message.success(t('common.createSuccess'))
      close()
      nextTick(()=> {
        push({ name: 'ProductSpuEdit', params: { id: resId } })
      })
    } else {
      await ProductSpuApi.updateSpu(deepCopyFormData)
      message.success(t('common.updateSuccess'))
      close()
    }
  } catch (e) {
    formLoading.value = false;
  }
}

/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
onMounted(async () => {
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id')
  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()

  let currencyRes = await ExchangeRateApi.getExchangeRatePage({
    pageNo: 1,
    pageSize: 100
  });
  currencyList.value = currencyRes.list;

  await getDetail();
})
</script>
